import logging
import os
import sys

import facade
from xjlibrary.mrequest import baserequest
# 禁用安全请求警告
from xjlibrary.our_file_dir import BaseDir, ImageFile

curPath = BaseDir.get_file_dir_absolute(__file__)
TopPath = BaseDir.get_upper_dir(curPath, -2)
sPath = BaseDir.get_new_path(TopPath, "download", "cell", "download", "cover")

absurl = []
BaseUrls = "https://www.cell.com"
HEADERS = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
           'Accept-Encoding': 'gzip, deflate, br', 'Connection': 'keep-alive',
           'Accept-Language': 'zh-CN,zh;q=0.9', 'Cache-Control': 'max-age=0',
           'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '
                         'Chrome/66.0.3359.139 Safari/537.36', }

mysqlutils = facade.MysqlUtiles(BaseDir.get_new_path(curPath, "db.ini"), "db", facade.get_streamlogger())


# def down_index():
#     """下载索引页"""
#     if not os.path.exists(FILE_DOWNLOAD_PATH):
#         os.makedirs(FILE_DOWNLOAD_PATH)
#
# def time_details_index():
#     """时间索引详情页"""
#     if not os.path.exists(DIR_TIME_DETAILS):
#         os.makedirs(DIR_TIME_DETAILS)
# # 数据库链接
# def MajorDbConnect():
#     return MySqlDbConnect(curPath, "db.ini")


def SelectListFromDB():
    global ListSqls
    # 数据库连接
    # conn = MajorDbConnect()
    sSql = "SELECT `cover_url`,`url` FROM `journal` WHERE `stat` != 2"
    # rows = SelctSqlFromDB(sSql, conn)
    rows = mysqlutils.SelectFromDB(sSql)
    return rows


def get_url(url, endstring=""):
    BoolResult, errString, r = baserequest.BaseRequest(url, endstring=endstring, timeout=15)
    if not BoolResult:
        sys.exit(-1)
    return r


def save_file(outfile, r):
    if ImageFile.img_to_format_jpg(r.content, outfile):
        print("保存图片成功")
    else:
        print("保存文件失败,请检查")
        sys.exit(-1)


def get_list_url(rows):
    global absurl, nCount
    for cover_url, url2 in rows:
        if not cover_url:
            continue
        if cover_url.startswith("//"):
            url="https:"+cover_url
        else:
            url = BaseUrls + cover_url
        list_url = url2.split("/")
        names = list_url[-2]
        name = names + ".jpg"  # "celljournal@"+name+"★/smartlib/celljournal/"
        outfile = "{}/{}".format(sPath, name)
        print(outfile)
        if not os.path.exists(sPath):
            os.makedirs(sPath)
        if os.path.exists(outfile):
            print("文件存在{}".format(outfile))
            continue
        r = get_url(url)
        save_file(outfile, r)


def main(logger1: logging.Logger = None):
    global logger
    logger = logger1
    rows = SelectListFromDB()
    get_list_url(rows)


if __name__ == "__main__":
    main()
